<template>
  <div class="mui-numbox" data-numbox-min="1" :data-numbox-max="max" :style="myStyle">
    <button class="mui-btn mui-btn-numbox-minus" type="button">-</button>
    <input class="mui-input-numbox" type="number" :value="initcount" @change="countChanged" ref="num">
    <button class="mui-btn mui-btn-numbox-plus" type="button">+</button>
  </div>
</template>

<script>
import mui from '../lib/mui/js/mui.min.js'

export default {
  data() {
    return {
      myStyle: {}
    }
  },
  mounted() {
    // 确保 mui 库已正确加载
    if (typeof mui !== 'undefined' && mui) {
      mui('.mui-numbox').numbox()
    } else {
      console.error('mui 库未正确加载')
    }

    // 根据 size 属性设置样式
    if (this.$props.size === 'min') {
      this.myStyle = { height: '25px', margin: '0 10px 0 10px' }
    }
  },
  methods: {
    countChanged() {
      const count = parseInt(this.$refs.num.value, 10)
      if (!isNaN(count)) {
        this.$emit('count', { id: this.goodsid, count: count })
      } else {
        console.error('输入的值不是有效的数字')
      }
    }
  },
  props: ['initcount', 'max', 'goodsid', 'size'],
  watch: {
    'max'(newVal) {
      if (typeof mui !== 'undefined' && mui) {
        mui('.mui-numbox').numbox().setOption('max', newVal)
      } else {
        console.error('mui 库未正确加载')
      }
    }
  }
}
</script>

<style scoped>
.mui-numbox {
  display: flex;
  align-items: center;
}

.mui-btn-numbox-minus,
.mui-btn-numbox-plus {
  width: 30px;
  height: 30px;
  border: 1px solid #ccc;
  background-color: #fff;
  cursor: pointer;
}

.mui-input-numbox {
  width: 50px;
  height: 30px;
  text-align: center;
  border: 1px solid #ccc;
  margin: 0 5px;
}
</style>